import 'dart:async';

import 'package:flutter/foundation.dart'; // 用于 kIsWeb
import 'package:flutter/material.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:xrenovation/api/subscription.api.dart';
import 'package:xrenovation/localization/app_localizations.dart';
import 'package:xrenovation/widgets/custom_button.dart';

class SubscriptionPage extends StatefulWidget {
  const SubscriptionPage({super.key});

  @override
  State<SubscriptionPage> createState() => _SubscriptionPageState();
}

class _SubscriptionPageState extends State<SubscriptionPage> {
  final InAppPurchase _iap = InAppPurchase.instance;
  late StreamSubscription<List<PurchaseDetails>> _subscription;
  List<ProductDetails> _products = [];
  bool _isLoading = true;
  bool _purchasing = false;
  String? _currentSubscriptionId;

  // 判断是否原生平台（iOS/Android）
  bool get _isNativePlatform =>
      !kIsWeb && (defaultTargetPlatform == TargetPlatform.iOS || defaultTargetPlatform == TargetPlatform.android);

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);
    final isDarkMode = theme.brightness == Brightness.dark;

    return Scaffold(
      appBar: AppBar(
        title: Text(localizations.translate('subscription_title')),
        actions: [
          if (_isNativePlatform) // 只在原生平台显示恢复购买按钮
            TextButton(onPressed: _restorePurchases, child: Text(localizations.translate('restore_purchases'))),
        ],
      ),
      body:
          _isLoading
              ? const Center(child: CircularProgressIndicator())
              : SingleChildScrollView(
                padding: const EdgeInsets.all(20),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 标题和描述
                    Text(
                      localizations.translate('choose_plan'),
                      style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    Text(
                      localizations.translate('subscription_description'),
                      style: TextStyle(fontSize: 16, color: theme.hintColor),
                    ),
                    const SizedBox(height: 24),

                    // 免费试用卡片
                    _buildPlanCard(
                      title: localizations.translate('free_trial'),
                      price: localizations.translate('free'),
                      duration: localizations.translate('7_days'),
                      features: [
                        localizations.translate('feature1'),
                        localizations.translate('feature2'),
                        localizations.translate('feature3'),
                      ],
                      isCurrent: _currentSubscriptionId == 'free_trial_7days',
                      isRecommended: false,
                      onPressed: _startFreeTrial,
                    ),
                    const SizedBox(height: 16),

                    // 月度订阅卡片
                    _buildPlanCard(
                      title: localizations.translate('monthly_subscription'),
                      price: '\$30',
                      duration: localizations.translate('per_month'),
                      features: [
                        localizations.translate('feature1'),
                        localizations.translate('feature2'),
                        localizations.translate('feature3'),
                        localizations.translate('feature4'),
                      ],
                      isCurrent: _currentSubscriptionId == 'monthly',
                      isRecommended: true,
                      onPressed: () => _purchaseSubscription('monthly'),
                    ),
                    const SizedBox(height: 16),

                    // 年度订阅卡片
                    _buildPlanCard(
                      title: localizations.translate('yearly_subscription'),
                      price: '\$300',
                      duration: localizations.translate('per_year'),
                      features: [
                        localizations.translate('feature1'),
                        localizations.translate('feature2'),
                        localizations.translate('feature3'),
                        localizations.translate('feature4'),
                        localizations.translate('feature5'),
                      ],
                      isCurrent: _currentSubscriptionId == 'yearly',
                      isRecommended: false,
                      onPressed: () => _purchaseSubscription('yearly'),
                    ),
                    const SizedBox(height: 24),

                    // 条款说明
                    Text(
                      localizations.translate('subscription_terms'),
                      style: TextStyle(fontSize: 12, color: theme.hintColor),
                      textAlign: TextAlign.center,
                    ),
                    const SizedBox(height: 8),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        TextButton(
                          onPressed: () => Navigator.pushNamed(context, '/privacyPolicy'),
                          child: Text(localizations.translate('privacy_policy')),
                        ),
                        Text('|', style: TextStyle(color: theme.hintColor)),
                        TextButton(
                          onPressed: () => Navigator.pushNamed(context, '/termsService'),
                          child: Text(localizations.translate('terms_of_service')),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
    );
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _initPurchase();
    _loadSubscriptionStatus();
  }

  Widget _buildPlanCard({
    required String title,
    required String price,
    required String duration,
    required List<String> features,
    bool isCurrent = false,
    bool isRecommended = false,
    VoidCallback? onPressed,
  }) {
    final theme = Theme.of(context);
    final isDarkMode = theme.brightness == Brightness.dark;

    return Card(
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
        side: isCurrent ? BorderSide(color: theme.primaryColor, width: 2) : BorderSide.none,
      ),
      child: Container(
        padding: const EdgeInsets.all(20),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(12),
          gradient:
              isRecommended
                  ? LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    colors: [theme.primaryColor.withOpacity(0.1), theme.primaryColor.withOpacity(0.05)],
                  )
                  : null,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (isRecommended)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(color: theme.colorScheme.error, borderRadius: BorderRadius.circular(4)),
                child: Text(
                  AppLocalizations.of(context).translate('recommended'),
                  style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold),
                ),
              ),
            if (isRecommended) const SizedBox(height: 8),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                if (isCurrent)
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                    decoration: BoxDecoration(
                      color: theme.primaryColor.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Text(
                      AppLocalizations.of(context).translate('current_plan'),
                      style: TextStyle(color: theme.primaryColor, fontSize: 12),
                    ),
                  ),
              ],
            ),
            const SizedBox(height: 8),
            Text(price, style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold)),
            Text(duration, style: TextStyle(fontSize: 14, color: theme.hintColor)),
            const SizedBox(height: 16),
            ...features.map(
              (feature) => Padding(
                padding: const EdgeInsets.symmetric(vertical: 4),
                child: Row(
                  children: [
                    Icon(Icons.check_circle, size: 16, color: theme.primaryColor),
                    const SizedBox(width: 8),
                    Expanded(child: Text(feature)),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 16),
            CustomButton(
              title:
                  isCurrent
                      ? AppLocalizations.of(context).translate('current_plan')
                      : AppLocalizations.of(context).translate('subscribe_now'),
              onTap: isCurrent ? null : onPressed,
              isLoading: _purchasing,
            ),
          ],
        ),
      ),
    );
  }

  void _handlePurchaseUpdate(List<PurchaseDetails> purchases) async {
    for (final purchase in purchases) {
      if (purchase.status == PurchaseStatus.pending) {
        // 购买处理中
        setState(() => _purchasing = true);
      } else if (purchase.status == PurchaseStatus.purchased || purchase.status == PurchaseStatus.restored) {
        // 购买成功或恢复购买
        await _verifyPurchase(purchase);
      } else if (purchase.status == PurchaseStatus.error) {
        // 购买失败
        setState(() => _purchasing = false);
        _showError('Purchase failed: ${purchase.error?.message}');
      }

      // 完成购买流程
      if (purchase.pendingCompletePurchase) {
        await _iap.completePurchase(purchase);
      }
    }
  }

  Future<void> _handleWebPayment(String productId) async {
    // 这里实现Web支付逻辑，比如调用Stripe等支付网关
    debugPrint('Web payment for $productId');
    // 模拟支付成功
    await Future.delayed(const Duration(seconds: 1));
  }

  Future<void> _handleWebRestore() async {
    // 这里实现Web平台的恢复购买逻辑
    debugPrint('Web restore purchases');
    // 模拟恢复成功
    await Future.delayed(const Duration(seconds: 1));
  }

  Future<void> _initPurchase() async {
    // Web平台不支持应用内购买
    if (!_isNativePlatform) {
      setState(() => _isLoading = false);
      return;
    }

    // 检查支付是否可用
    final bool available = await _iap.isAvailable();
    if (!available) {
      setState(() => _isLoading = false);
      return;
    }

    // 监听购买状态变化
    _subscription = _iap.purchaseStream.listen(
      _handlePurchaseUpdate,
      onDone: () => _subscription.cancel(),
      onError: (error) => debugPrint('Purchase error: $error'),
    );

    // 获取产品信息
    await _loadProducts();
  }

  Future<void> _loadProducts() async {
    try {
      // 从后端获取产品ID列表
      final response = await SubscriptionApi.getProducts();
      final productIds = response['data'] as List<dynamic>;

      // 查询应用商店中的产品详情
      final ProductDetailsResponse productDetails = await _iap.queryProductDetails(productIds.cast<String>().toSet());

      if (mounted) {
        setState(() {
          _products = productDetails.productDetails;
          _isLoading = false;
        });
      }
    } catch (e) {
      debugPrint('Failed to load products: $e');
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _loadSubscriptionStatus() async {
    try {
      final response = await SubscriptionApi.getSubscriptionStatus();
      if (mounted) {
        setState(() {
          _currentSubscriptionId = response['data']['product_id'];
        });
      }
    } catch (e) {
      debugPrint('Failed to load subscription status: $e');
    }
  }

  Future<void> _purchaseSubscription(String productId) async {
    try {
      setState(() => _purchasing = true);

      if (kIsWeb) {
        // Web平台的特殊处理
        await _handleWebPayment(productId);
        setState(() => _purchasing = false);
      } else {
        // 原生平台处理
        final product = _products.firstWhere((p) => p.id == productId);
        final PurchaseParam purchaseParam = PurchaseParam(productDetails: product);

        if (defaultTargetPlatform == TargetPlatform.android) {
          // Android使用Google Play结算
          await _iap.buyConsumable(purchaseParam: purchaseParam);
        } else {
          // iOS使用应用内购买
          await _iap.buyNonConsumable(purchaseParam: purchaseParam);
        }
      }

      // 更新订阅状态
      await _loadSubscriptionStatus();
    } catch (e) {
      debugPrint('Purchase error: $e');
      if (mounted) {
        setState(() => _purchasing = false);
      }
      _showError('Purchase failed: ${e.toString()}');
    }
  }

  Future<void> _restorePurchases() async {
    try {
      setState(() => _purchasing = true);

      if (kIsWeb) {
        // Web平台的特殊处理
        await _handleWebRestore();
      } else if (defaultTargetPlatform == TargetPlatform.iOS) {
        // iOS恢复购买
        await _iap.restorePurchases();
      } else {
        // Android或其他平台调用API恢复
        await SubscriptionApi.restorePurchases();
      }

      await _loadSubscriptionStatus();
    } catch (e) {
      debugPrint('Failed to restore purchases: $e');
      _showError('Failed to restore purchases');
    } finally {
      if (mounted) {
        setState(() => _purchasing = false);
      }
    }
  }

  void _showError(String message) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(message)));
  }

  Future<void> _startFreeTrial() async {
    try {
      setState(() => _purchasing = true);

      if (_currentSubscriptionId != null) {
        _showError('Sorry, you are currently in the subscription process');
        return;
      }

      // 调用API开始免费试用
      final response = await SubscriptionApi.freeTrial('free_trial', 'free_trial_7days', 'your.package.name');

      if (response['code'] == 200) {
        if (mounted) {
          setState(() {
            _currentSubscriptionId = 'free_trial_7days';
          });
        }
      } else {
        _showError(response['message']);
      }
      setState(() {
        _purchasing = false;
      });
    } catch (e) {
      debugPrint('Failed to start free trial: $e');
      if (mounted) {
        setState(() => _purchasing = false);
      }
      _showError('Failed to start free trial');
    }
  }

  Future<void> _verifyPurchase(PurchaseDetails purchase) async {
    try {
      // Web平台跳过验证
      if (kIsWeb) {
        if (mounted) {
          setState(() {
            _purchasing = false;
            _currentSubscriptionId = purchase.productID;
          });
        }
        return;
      }

      // 原生平台验证
      if (defaultTargetPlatform == TargetPlatform.iOS) {
        final receiptData = purchase.verificationData.serverVerificationData;
        await SubscriptionApi.verifyIosReceipt(
          receiptData,
          isSandbox: false, // 生产环境设为false
        );
      } else if (defaultTargetPlatform == TargetPlatform.android) {
        await SubscriptionApi.verifyGooglePlayOrder(
          purchase.verificationData.serverVerificationData,
          purchase.productID,
          'your.package.name', // 替换为你的包名
        );
      }

      // 更新UI
      if (mounted) {
        setState(() {
          _purchasing = false;
          _currentSubscriptionId = purchase.productID;
        });
      }
    } catch (e) {
      debugPrint('Failed to verify purchase: $e');
      if (mounted) {
        setState(() => _purchasing = false);
      }
      _showError('Failed to verify purchase');
    }
  }
}
